package com.atguigu.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("插入的自动填充~~~~");

        //填充创建时间
        this.strictInsertFill(metaObject,"createTime", LocalDateTime.class, LocalDateTime.now());
        //填充更新时间
        this.strictInsertFill(metaObject,"updateTime",LocalDateTime.class, LocalDateTime.now());

        //设置作者的自动插入
        /*
        * 自动填充优化方案一：当拥有这个属性的时候再去进行填充
        * 自动填充优化方案二：当在业务层没有设置属性值的时候再去填充
        * */


        if (metaObject.hasSetter("author")){
            this.strictInsertFill(metaObject,"author",String.class,"彭于晏");
        }
        log.info("================================插入作者=============================");
        this.strictInsertFill(metaObject,"author",String.class,"啦啦啦");


        Object age = this.getFieldValByName("age", metaObject);
        if (age==null){
            this.strictInsertFill(metaObject,"age",Integer.class,22);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("更新的自动填充~~~~");
        //填充更新时间
        this.strictUpdateFill(metaObject,"updateTime",LocalDateTime.class,LocalDateTime.now());


    }
}
